package com.luokangtao.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luokangtao.common.handler.BaseException;
import com.luokangtao.common.util.MD5Util;
import com.luokangtao.user.entity.User;
import com.luokangtao.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * 用户登陆/退出相关接口
 * @author luokangtao
 * @create 2019-07-23 17:05
 */
@Service
public class SysService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户信息
     * @param loginname  用户登陆名
     * @param password  用户密码
     * @return
     */
    public User findByLoginNameAndPassword(String loginname, String password) {
        //组装查询条件
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("loginname",loginname);
        //查询当前登陆名的用户信息
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new BaseException("帐号不存在");
        }
        if(user.getStatus().equals("0")){
            throw new BaseException("帐号异常,请联系客户中心");
        }
        boolean checkPassword =false;
        try {
            //参数1:当前输入密码 参数2:数据库里面保存的MD5加盐密码
            checkPassword = MD5Util.validPasswd(password, user.getPassword());
        } catch (Exception e) {
            throw new BaseException("登陆异常");
        }
        if(!checkPassword){
            throw new BaseException("密码错误");
        }
        return user;
    }
}
